<?php
//decode by http://奥森世纪/
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2018/1/19
 * Time: 19:34
 */

namespace app\home\controller;
use app\home\model\Member;
use think\Db;
use think\Cache;

class Invite extends Base{

	public function __construct(){
		parent::__construct();

		$this->member = $this->checkLogin();
	}

    public function index(){
    
        $money = \app\admin\model\InvitationRebateRecord::getTotalMoney($this->member['uid']);
        $member_check = Db::name("member")->where("uid = {$this->member['uid']}")->find();
        $count= Db::name("member")->where("parent_uid = {$this->member['uid']}")->count();
      $config = Db::name('config')->find();
      

       $config['setting'] = json_decode($config['setting'],true);
      $linkregis = $config['setting']['linkregis'];
       $url =$linkregis."?member=".$this->member['uid'];
            //$imgs = $this->qrcode($url);
            //$datt['img'] = $imgs;
           //$res = Db::name("member")->where("uid = {$this->member['uid']}")->update($datt);
      
        /*if($member_check['img'] == ''||empty($member_check['img'])){
            $yuming = "http://".$_SERVER['SERVER_NAME'];
            $url = $yuming."/home/auth/register.html?i=".$this->member['uid'];
           
        }else{
            $imgs = $member_check['img'];
        }*/
        // vip 
        
        if($member_check['level'] > 1){
            $one_rebate = $config['setting']['invitation_vip_one_rebate'];
            $two_rebate = $config['setting']['invitation_vip_two_rebate'];
            $three_rebate = $config['setting']['invitation_vip_three_rebate']; 
        }else{
            $one_rebate = $config['setting']['invitation_one_rebate'];
            $two_rebate = $config['setting']['invitation_two_rebate'];
            $three_rebate = $config['setting']['invitation_three_rebate'];            
        }
        //邀请好友排行榜
        $month=date('m');
        $uid=$this->member['uid'];
   
        $rank=$this->reward_ajax();

		$is_reward=[];
        foreach($rank as $kk=>$vv){
	        if($uid == $vv['uid']){
	        	$is_reward=$vv;
	        	$is_reward['rank']=$kk+1;
	        }
        }
      
	        
		//接单数量
        
        $task_count=db('task_join')->where(['uid'=>$uid])->count();
        $parent3_uids = [];
        //徒孙人数
        $down_uids=db('member')->where(['parent_uid'=>$uid])->column('uid');
       if($down_uids){
        	$grandson=db('member')->where(['parent_uid'=>['in',$down_uids]])->count();
	        $grandson_uids=db('member')->where(['parent_uid'=>['in',$down_uids]])->column('uid');
            
            $parent3_uids = db('member')->where(['parent_uid'=>['in',$grandson_uids]])->column('uid');
	        
       }else{
	       	$grandson=0;
	       	$grandson_uids=[];
	       	$parent3_uids = [];
       }
   

        
        $grandson_uid_str=implode(',',$grandson_uids);
        //总收入
        
        $all_uids=array_merge($down_uids,$grandson_uids);
        
        $total_money=db('invitation_rebate_record')->where(['uid'=>$uid,'tuijian_id'=>['in',$all_uids]])->sum('num');
        
        return $this->fetch(__FUNCTION__, [
        
            'is_reward'=>$is_reward,
            
            'month' => $month,    
            'money' => $money,
          	'linkregis'=>$config['setting']['linkregis'],
            'domain' => $this->get_domain(),
           // 'img' => $imgs,
            'count'=>$count,
            'member'=>$member_check,
            'task_count'=>$task_count,
            'grandson'=>$grandson,
            'parent3' =>count($parent3_uids),
            'total_money'=>$total_money,
            'one_rebate' =>$one_rebate,
            'two_rebate' =>$two_rebate,
            'three_rebate' =>$three_rebate,
      
        ]);
    }
    
    public function remark(){
    
        $money = \app\admin\model\InvitationRebateRecord::getTotalMoney($this->member['uid']);
        $member_check = Db::name("member")->where("uid = {$this->member['uid']}")->find();
        $count= Db::name("member")->where("parent_uid = {$this->member['uid']}")->count();
      $config = Db::name('config')->find();
      

       $config['setting'] = json_decode($config['setting'],true);
      $linkregis = $config['setting']['linkregis'];
       $url =$linkregis."?member=".$this->member['uid'];
            //$imgs = $this->qrcode($url);
            //$datt['img'] = $imgs;
           //$res = Db::name("member")->where("uid = {$this->member['uid']}")->update($datt);
      
        /*if($member_check['img'] == ''||empty($member_check['img'])){
            $yuming = "http://".$_SERVER['SERVER_NAME'];
            $url = $yuming."/home/auth/register.html?i=".$this->member['uid'];
           
        }else{
            $imgs = $member_check['img'];
        }*/
        // vip 
        
        if($member_check['level'] > 1){
            $one_rebate = $config['setting']['invitation_vip_one_rebate'];
            $two_rebate = $config['setting']['invitation_vip_two_rebate'];
            $three_rebate = $config['setting']['invitation_vip_three_rebate']; 
        }else{
            $one_rebate = $config['setting']['invitation_one_rebate'];
            $two_rebate = $config['setting']['invitation_two_rebate'];
            $three_rebate = $config['setting']['invitation_three_rebate'];            
        }
        //邀请好友排行榜
        $month=date('m');
        $uid=$this->member['uid'];
   
        $rank=$this->reward_ajax();

		$is_reward=[];
        foreach($rank as $kk=>$vv){
	        if($uid == $vv['uid']){
	        	$is_reward=$vv;
	        	$is_reward['rank']=$kk+1;
	        }
        }
      
	        
		//接单数量
        
        $task_count=db('task_join')->where(['uid'=>$uid])->count();
        $parent3_uids = [];
        //徒孙人数
        $down_uids=db('member')->where(['parent_uid'=>$uid])->column('uid');
       if($down_uids){
        	$grandson=db('member')->where(['parent_uid'=>['in',$down_uids]])->count();
	        $grandson_uids=db('member')->where(['parent_uid'=>['in',$down_uids]])->column('uid');
            
            $parent3_uids = db('member')->where(['parent_uid'=>['in',$grandson_uids]])->column('uid');
	        
       }else{
	       	$grandson=0;
	       	$grandson_uids=[];
	       	$parent3_uids = [];
       }
   

        
        $grandson_uid_str=implode(',',$grandson_uids);
        //总收入
        
        $all_uids=array_merge($down_uids,$grandson_uids);
        
        $total_money=db('invitation_rebate_record')->where(['uid'=>$uid,'tuijian_id'=>['in',$all_uids]])->sum('num');
        
        return $this->fetch(__FUNCTION__, [
        
            'is_reward'=>$is_reward,
            
            'month' => $month,    
            'money' => $money,
          	'linkregis'=>$config['setting']['linkregis'],
            'domain' => $this->get_domain(),
           // 'img' => $imgs,
            'count'=>$count,
            'member'=>$member_check,
            'task_count'=>$task_count,
            'grandson'=>$grandson,
            'parent3' =>count($parent3_uids),
            'total_money'=>$total_money,
            'one_rebate' =>$one_rebate,
            'two_rebate' =>$two_rebate,
            'three_rebate' =>$three_rebate,
      
        ]);
    }



    public function reward_ajax(){

      $request=request();
      $page=$request->param('page');
        $start=10*($page-1);

		$rank_ajax_data=Cache::get('rank_ajax_data');

		$rank='';
		if(!$rank_ajax_data){
		    
	        //邀请好友排行榜
	       // $month=date('m');
	       //  $this_month=strtotime(date('Y-m'));
			controller('account')->invite_cheat();
	      //file_get_contents('https://wap.Wacp.top/home/account/invite_cheat');
	      
		}

			$rank_ajax_data=Cache::get('rank_ajax_data');

			$rank=json_decode($rank_ajax_data,true);
//dump($rank);
//dump(array_slice($rank,$start,10));

		 if(request()->isAjax()){
		 	
	        return $this->fetch(__FUNCTION__, [
	            'list'=>array_slice($rank,$start,10),
	          ]);
		 }else{
		 	return $rank;
		 }

    }


    public function weekly_ajax(){
    	
    	return controller('account')->weekly_ajax();
    }

	public function get_nickname($nickname){
	
		if(!$nickname) return $nickname;
		 $length=floor(strlen($nickname)/2)-3;
		 $nickname=mb_substr($nickname,0,2) . str_repeat('*',$length>0?:0);
		 return $nickname;
		 
	}



    public function weekly(){
       
		$this_monday= date('Y-m-d',(time()-((date('w',time())==0?7:date('w',time()))-1)*24*3600));
			
	        $this_week=strtotime($this_monday);
	        $where=[
	          'a.create_time'=>['gt',$this_week],
	          'status'=>3,
	          'a.uid'=>$this->member['uid'],
	        ];
	        
	   $member_task=db('task_join')->alias('a')->field("count(a.id) as count,a.uid,b.nickname,sum(unit_price) as total_price")->join('member b','a.uid=b.uid')->join('task c',' a.task_id=c.id')->where($where)->select();




		//上周接单

		$last_start_monday= date('Y-m-d',(time()-((date('w',time())==0?7:date('w',time()))-1)*24*3600)-3600*24*7);
		$last_end_monday= date('Y-m-d',(time()-((date('w',time())==0?7:date('w',time()))-1)*24*3600));
			
	        $last_week_start=strtotime($last_start_monday);
	        $last_week_end=strtotime($last_end_monday);
	        $where=[
	          'a.create_time'=>['between',[$last_week_start,$last_week_end]],
	          'status'=>3,
	          'a.uid'=>$this->member['uid'],
	        ];
	        
	   $last_member_task=db('task_join')->alias('a')->field("count(a.id) as count,a.uid,b.nickname,sum(unit_price) as total_price")->join('member b','a.uid=b.uid')->join('task c',' a.task_id=c.id')->where($where)->select();
	   

	//是否获奖
		$last_reward=db('weekly_record')->where(['uid'=>$this->member['uid'],'reward_time'=>$last_week_end])->find();




        //邀请好友排行榜
 
        $uid=$this->member['uid'];
        
        $rank=$this->weekly_ajax();
		$is_reward=[];
        foreach($rank as $kk=>$vv){
	        if($uid == $vv['uid']){
	        	$is_reward=$vv;
	        	$is_reward['rank']=$kk+1;
	        }
        }
	        
        
        return $this->fetch(__FUNCTION__, [
        
            'is_reward'=>$is_reward,
            'last_reward'=>$last_reward,
            'list'=>$rank,
            'member'=>$this->member,
    		'member_task'=>$member_task[0],
    		'last_member_task'=>$last_member_task[0]
    		
        ]);
    }
    
     public function weekly_shouru(){
       
		$this_monday= date('Y-m-d',(time()-((date('w',time())==0?7:date('w',time()))-1)*24*3600));
			
	        $this_week=strtotime($this_monday);
	        $where=[
	          'a.create_time'=>['gt',$this_week],
	          'status'=>3,
	          'a.uid'=>$this->member['uid'],
	        ];
	        
	   $member_task=db('task_join')->alias('a')->field("count(a.id) as count,a.uid,b.nickname,sum(unit_price) as total_price")->join('member b','a.uid=b.uid')->join('task c',' a.task_id=c.id')->where($where)->select();




		//上周接单

		$last_start_monday= date('Y-m-d',(time()-((date('w',time())==0?7:date('w',time()))-1)*24*3600)-3600*24*7);
		$last_end_monday= date('Y-m-d',(time()-((date('w',time())==0?7:date('w',time()))-1)*24*3600));
			
	        $last_week_start=strtotime($last_start_monday);
	        $last_week_end=strtotime($last_end_monday);
	        $where=[
	          'a.create_time'=>['between',[$last_week_start,$last_week_end]],
	          'status'=>3,
	          'a.uid'=>$this->member['uid'],
	        ];
	        
	   $last_member_task=db('task_join')->alias('a')->field("count(a.id) as count,a.uid,b.nickname,sum(unit_price) as total_price")->join('member b','a.uid=b.uid')->join('task c',' a.task_id=c.id')->where($where)->select();
	   

	//是否获奖
		$last_reward=db('weekly_record')->where(['uid'=>$this->member['uid'],'reward_time'=>$last_week_end])->find();




        //邀请好友排行榜
 
        $uid=$this->member['uid'];
        
        $rank=$this->weekly_ajax();
		$is_reward=[];
        foreach($rank as $kk=>$vv){
	        if($uid == $vv['uid']){
	        	$is_reward=$vv;
	        	$is_reward['rank']=$kk+1;
	        }
        }
        
        //收入排行task_join表  
        $ph = controller('account')->weekly_ajax_shouru();
	        
        
        return $this->fetch(__FUNCTION__, [
        
            'is_reward'=>$is_reward,
            'last_reward'=>$last_reward,
            'list'=>$ph,
            'member'=>$this->member,
    		'member_task'=>$member_task[0],
    		'last_member_task'=>$last_member_task[0]
    		
        ]);
    }

    public function last_weekly(){
       
       
        $request=request();
    	$page=$request->param('page');
        $start=10*($page-1);
        
		$this_monday= time()-((date('w',time())==0?7:date('w',time()))-1)*24*3600;
		$last_monday=date('Y-m-d',$this_monday-24*3600*7);
		$task_weekly=db('weekly_record')->alias('a')->where(['reward_time'=>$last_monday])->join('member b','a.uid = b.uid')->order('task_weekly_id asc')->select();
	
	        foreach($task_weekly as &$vv){
		       $vv['nickname']=$this->get_nickname($vv['nickname']);
	        }
        
	
		  return $this->fetch('weekly_ajax', [
            'list'=>array_slice($task_weekly,$start,10),
          ]);
		          
		          
		
    }




    ////二维码生成
    function qrcode($url,$level=3,$size=4){
                $PNG_TEMP_DIR = "./img/";  
              Vendor('phpqrcode.phpqrcode');
              $errorCorrectionLevel =intval($level) ;//容错级别 
              $matrixPointSize = intval($size);//生成图片大小 
            //生成二维码图片 
              $filename = $PNG_TEMP_DIR."tp".time().rand(1,100).".png";

              //echo $_SERVER['REQUEST_URI'];
              $object = new \QRcode();
              ob_end_clean();
              $object->png($url, $filename, $errorCorrectionLevel, $matrixPointSize, 2);   
            
              return basename($filename);
 }

    public function silver(){
      
      //徒子徒孙
        //徒孙人数
        $uid=$this->member['uid'];
        
        $down_arr=db('member')->where(['parent_uid'=>$uid])->select();
       
        $down_uids=db('member')->where(['parent_uid'=>$uid])->column('uid');
        
        $down=db('member')->where(['parent_uid'=>$uid])->count();
        
        $parent3_uids = [];
        $parent3_count = 0;
       if($down_uids){
        	$grandson=db('member')->where(['parent_uid'=>['in',$down_uids]])->count();
        	
	        $grandson_arr=db('member')->where(['parent_uid'=>['in',$down_uids]])->select();
	        
	        if($grandson_arr){
	            foreach ($grandson_arr as $v){
	                $parent3_uids[] = $v['uid'];
	            }
	            
	            if($parent3_uids){
	                 $parent3_count = db('member')->where(['parent_uid'=>['in',$parent3_uids]])->count();
	            }
	        }
	        
       }else{
            $parent3_count = 0;
	       	$grandson=0;
	       	$grandson_uids=[];
	       	$grandson_arr=[];
       }

    	
        //$all_users=array_merge($down_arr,$grandson_arr);
        $type=input('type');
        if($type == 1 || !$type){
        	$all_users=$down_arr;
        	$type =1;
        }
        
        if($type == 2){
        	$all_users=$grandson_arr;
        }
        
        if($type == 3){
            if(!empty($parent3_uids)){
                $all_users = db('member')->where(['parent_uid'=>['in',$parent3_uids]])->select();
            }else{
                $all_users = [];
            }
        }
        
        
        
        	$model=db('invitation_rebate_record');
        	
        	$list=[];
        	
            foreach($all_users as &$v){
        		$v['sum']=$model->where(['uid'=>$uid,'tuijian_id'=>$v['uid']])->sum('num');
        		$v['time']=date("Y-m-d",$v['create_time']);
	          if(empty($v['avatar'])) {
	              $v['avatar']="/uploads/avatar.png";
	          }
        }
        	
    //  var_dump(count($parent3_uids));exit;
        return $this->fetch(__FUNCTION__, [
            'list' => $all_users,
            'down'=>$down?:0,
            'grandson'=>$grandson?:0,
            'parent3' => $parent3_count,
            'type'=>$type
        ]);
    }

    public function silver_ajax() {
    //  var_dump($_REQUEST['page']);
      if($_REQUEST['page'] > 1){
        die;
      }





        $uid=$this->member['uid'];
        
        $down_uids=db('member')->where(['parent_uid'=>$uid])->select();
       if($down_uids){
        	$grandson=db('member')->where(['parent_uid'=>['in',$down_uids]])->count();
	        $grandson_uids=db('member')->where(['parent_uid'=>['in',$down_uids]])->select();
       }else{
	       	$grandson=0;
	       	$grandson_uids=[];
       }
      
        $grandson_uid_str=implode(',',$grandson_uids);
        //总收入
        
        $all_users=array_merge($down_uids,$grandson_uids);
        
     
        
      
        	$model=db('invitation_rebate_record');
            foreach($all_uids as &$v){
        		$v['sum']=$model->where(['uid'=>$uid,'tuijian_id'=>$v['uid']])->sum('num');
        		
	          if(empty($v['avatar'])) {
	              $v['avatar']="/uploads/avatar.png";
	          }
        }
        
        














       if(is_array($onelist)){

            foreach ($onelist as $key => $value) {

                   $value['level_title'] = "一级";
                    $list[] = $value;
                    //$list[$key]['num']=$this->getNextUserGold($value['uid'],$this->member['uid']);
                    $list[$key]['num']=db('invitation_rebate_record')->where('tuijian_id',$value['uid'])->sum('num');
                    $jinbi = db('invite_petfh')->where('uid',$value['uid'])->where('fid',$this->member['uid'])->value('num');
                   $list[$key]['jinbi']= $jinbi?$jinbi:0;
                   
	                $list[$key]['time']=date("Y-m-d",$value['create_time']);
	                $list[$key]['username']=substr_replace($value['username'],'****',3,4);
	                if(empty($value['avatar']))
	                {
	                   $list[$key]['avatar']='http://'.$_SERVER['HTTP_HOST']."/uploads/avatar.png";
	                }

               }

       }

        to_json(0, '', $list);
    }

    public function gold(){
        return $this->fetch(__FUNCTION__);
    }

    public function gold_ajax() {
        $where = ['uid' => $this->member['uid']];
        $list = \app\admin\model\InvitationRebateRecord::getPagination($where, 15, NULL, "id DESC");

        to_json(0, '', $list);
    }

    //获取下级用户的返利
    public function getNextUserGold($uid,$parentid){
	    $res="";
	    if(!empty($uid))
        {
            $num=0;
            $where=['uid' =>$parentid];
            //$list=\app\admin\model\InvitationRebateRecord::getPagination($where, 150000, NULL, "id DESC");
            $list = db('invitation_rebate_record')->where('uid',$parentid)->field('tuijian_id,num')->select();
            foreach ($list as $key=>$value)
            {
                //$start=mb_strpos($list[0]['remark'],'[')+1;
                //$username=mb_substr($list[0]['remark'],$start,11,'utf-8');
                $usrinfo=Db::name("member")->where("uid = {$value['tuijian_id']}")->find();
                if($usrinfo['uid']==$uid)
                {
                    $num=bcadd($num,$value['num'],2);
                }
            }
            $res=round($num,2);
        }
	    return $res;
    }
    
    
    public function poster(){
        $config = Db::name('config')->find();
        $config['setting'] = json_decode($config['setting'],true);
        $linkregis = $config['setting']['linkregis'];
        $url =$linkregis."?member=".$this->member['uid'];

        return $this->fetch(__FUNCTION__, [
           'linkregis' => $linkregis,
           'member' => $this->member,
        ]);
    }
    
     public function share_reward(){
     	 $rst=Db::name("member")->where("uid = {$this->member['uid']}")->setField('is_share',1);
     	 if($rst){
     	 	return 1;
     	 }else{
     	 	return 0;
     	 }
     }
     
    
    
}